package cn.me.service.impl;

import cn.me.dao.SectionMapper;
import cn.me.dao.UserMapper;
import cn.me.pojo.Section;
import cn.me.pojo.User;
import cn.me.pojo.UserExample;
import cn.me.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper user;
    @Resource
    private SectionMapper section;
    @Autowired
    private PayServiceImpl payService;

    //模糊查询
    @Override
    public PageInfo<User> all(Integer uout,String name, Integer tid, Integer page, Integer size) {
        System.out.println(name+"--"+tid+"---"+page+"---"+size);
        //开启分页
        PageHelper.startPage(page,size);
        //添加查询条件
        UserExample example=new UserExample();
        UserExample.Criteria criteria=example.createCriteria();
        if (!name.trim().isEmpty()&&!name.equals("")){
            criteria.andUnameLike("%"+name+"%");
        }
        if (tid!=0){
            criteria.andUsectionEqualTo(tid);
        }
        if (uout<=1){
            criteria.andUoutEqualTo(uout);
        }

        //调用查询方法
        List<User> users = user.selectByExample(example);

        for (User user1 : users) {
            user1.setSection(section.selectByPrimaryKey(user1.getUsection()));
        }


        //把查询结果封装到分页插件中
        return new PageInfo<>(users);
    }

    @Override
    public void add(User u) {
        u.setUout(1);

        this.user.insertSelective(u);
    }

    @Override
    public User selectByUid(int id) {
        User u = this.user.selectByPrimaryKey(id);

        return u;
    }

    @Override
    public void toUpdate(User u) {

        user.updateByPrimaryKeySelective(u);
    }

    @Override
    public void delete(String[] ids) {
        List list1=Arrays.asList(ids);
        //添加条件
        UserExample example=new UserExample();
        example.createCriteria().andUidIn(list1);
        //执行删除
        for (int i=0;i<list1.size();i++){
            payService.delectBypuid(Integer.parseInt((String) list1.get(i)) );
        }
        user.deleteByExample(example);
    }
}
